<template>
  <div class="wts-container">
    <header class="modify-header">
      <div class="left">
        <span class="arrow" @click="exitAssignment"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>课程作业</span>
      </div>
      <div class="right">
        课程管理系统
      </div>
    </header>
    <div class="do-assignment">
      <!--题目容器-->
      <div style="width: 43%; height: 80%">
        <!--题目内容中心-->
        <div class="assignment-center">
          <!-- 查询框 -->
          <div class="right">
            <label style="margin-right: 10px">题目对应课程：</label>
            <el-select v-model="value" filterable placeholder="题目对应课程">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-button class="normal-btn continue" type="info" @click="getQuestion()" icon="el-icon-search">
              <span style="font-weight: bold;">查询</span>
            </el-button>
          </div>
          <!--题目信息-->
          <el-table :data="tableData" stripe class="data_table">
            <el-table-column prop="id" label="题目编号" align="center">
            </el-table-column>
            <el-table-column prop="questionContent" label="题目内容" align="center" width="100">
              <template slot-scope="scope">
                <span v-if="!scope.row.questionContent">无</span>
                <el-link v-else :href="scope.row.questionContent" type="primary" target="_blank"
                  class="underline-link"><i class="el-icon-folder-opened" style="font-size: 1.5em"></i></el-link>
              </template>
            </el-table-column>
            <el-table-column prop="questionTopicIntroduction" label="前言" align="center">
            </el-table-column>
            <el-table-column prop="questionType" label="题目类型" align="center">
            </el-table-column>
            <el-table-column prop="questionCourse" label="题目对应课程" align="center">
            </el-table-column>
            <el-table-column label="操作" align="center" style="width: 250px;">
              <template slot-scope="scope">
                <el-button type="text" size="small" class="delBut" @click="selectHandle('题目', scope.row.id, scope.row)">
                  选择题目
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="right">
            <el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="tablePage.pageNum"
              :page-size="tablePage.pageSize" :page-sizes="pageSizes" :total="tablePage.total"
              @size-change="handleSizeChange" @current-change="handlePageChange" />
          </div>
        </div>
      </div>
      <!--作业选择表-->
      <div style="width: 55%; height: 100%;" class="assignment-select">
        <el-table :data="assignmentListData" stripe>
          <el-table-column prop="id" label="作业编号" align="center">
          </el-table-column>
          <el-table-column prop="assignmentType" label="作业类型" align="center">
          </el-table-column>
          <el-table-column prop="assignmentContent" label="作业内容">
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间" align="center">
          </el-table-column>
          <el-table-column prop="endTime" label="截止时间" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" class="blueBug" @click="selectHandle('作业', scope.row.id, scope.row)">
                选择作业
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="right">
          <el-pagination @size-change="sizeChange" @current-change="currentChange" :current-page="page"
            :page-size="size" :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="total"
            style="float: right;">
          </el-pagination>
        </div>
        <div style="margin-right: 15px;">
          <el-button size="small" type="primary" @click="addHandle()">提交作业</el-button>
        </div>
      </div>
    <!-- 答题区 -->
      <el-dialog title="答题中" :visible.sync="dialogVisible" width="40%">
        <el-form ref="submittedAssignments" :model="submittedAssignments" class="form-table">
          <el-form-item label="题目编号" prop="questionId">
            <el-input v-model="submittedAssignments.questionId" disabled></el-input>
          </el-form-item>
          <el-form-item label="作业编号" prop="questionId">
            <el-input v-model="submittedAssignments.assignmentId" disabled></el-input>
          </el-form-item>
          <el-form-item label="作业文件" prop="submissioUrl">
            <el-upload class="upload-demo" :action="uploadUrl" ref="upload02" :on-success="handleSuccess"
              :on-error="handleError" :file-list="fileList" :limit="1" accept="*" list-type="text" :auto-upload="false">
              <el-button size="small" type="primary" icon="el-icon-folder-add">选择文件</el-button>
            </el-upload>
            <el-button style="margin-left: 5px" size="small" type="success" @click="submitUpload" icon="el-icon-upload">
              确认上传文件
            </el-button>
          </el-form-item>
          <el-form-item class="btn-container"> </el-form-item>
          <el-form-item>
            <span>选择文件后确认上传文件</span>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm()" icon="el-icon-check">提交作业</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// import CommentModel from "./CommentModel"; // 评论页面
import { getAssignmentAPI } from "@/api/assignment/assignment";
import { getQuestionAPI } from "@/api/question";
import { getUserIDLocalStorage } from "@/utils/utilLocalStorage";
import { addSubmittedAssignmentsAPI } from '@/api/submittedAssignments'

export default {
  name: "ViewAssignments",
  data() {
    return {
      courseId: '-1',
      groupIdInCourse: 1,
      assignmentList: {
        type: Array,
        // assignmentType: {},
        course: {}
      },
      tableData: [],
      // 题目分页
      tablePage: {
        pageNum: 1, // 第几页
        pageSize: 10, // 每页多少条
        total: 100 // 总记录数
      },
      options: [
        {
          value: '',
          label: '全部'
        }, {
          value: '计算机类',
          label: '计算机类'
        }, {
          value: '管理类',
          label: '管理类'
        }, {
          value: '理工类',
          label: '理工类'
        }, {
          value: '艺术类',
          label: '艺术类'
        }, {
          value: '其他',
          label: '其他'
        }],
      value: '',
      // 作业分页
      page: 1, //第几页
      size: 10, //一页多少条
      total: 0, //总条目数
      pageSizes: [5, 10, 20, 30], //可选择的一页多少条
      assignmentListData: [], // 作业表显示
      //文件上传路径
      uploadUrl: 'http://localhost:8081/file/upload',
      fileList: [], // 初始化文件列表
      // 提交作业
      submittedAssignments: {
        id: null,
        studentId: null,
        assignmentId: null,
        questionId: null,
        submissioUrl: null,
        grade: null,
      },
      // 答题弹窗
      dialogVisible: false
    }
  },
  components: {
    // CommentModel
  },
  created() {
    this.getTabelData2();
  },

  mounted() {
    // 从接口中获取数据
    this.courseId = this.$route.query.courseId;
    this.groupIdInCourse = this.$route.query.groupIdInCourse;
    this.getAssignments()
    this.getQuestion()
    this.submittedAssignments.studentId = getUserIDLocalStorage() // 本学生id
  },
  methods: {
    // 该课程作业
    getAssignments() {
      getAssignmentAPI(this.courseId).then((res) => {
        // console.log('获取该门课程作业：', res)
        this.assignmentList = res.data
        this.getTabelData()
      })
    },
    // 作业分页
    getTabelData() {
      //为全部数据
      this.assignmentListData = this.assignmentList.slice(
        (this.page - 1) * this.size,
        this.page * this.size
      );
      this.total = this.assignmentList.length
    },
    //获取表格数据，自行分页（splice）
    getTabelData2() {
      let data = JSON.parse(JSON.stringify(this.assignmentList))
      this.assignmentListData = data.splice(
        (this.page - 1) * this.size,
        this.size
      );
      this.total = this.assignmentList.length
    },
    //page改变时的回调函数，参数为当前页码
    currentChange(val) {
      console.log("翻页，当前为第几页", val);
      this.page = val;
      this.getTabelData2();
    },
    //size改变时回调的函数，参数为当前的size
    sizeChange(val) {
      console.log("改变每页多少条，当前一页多少条数据", val);
      this.size = val;
      this.page = 1;
      this.getTabelData2();
    },
    // 题目选择页面
    handlePageChange(currentPage) {
      this.tablePage.pageNum = currentPage
      // 在此刷新数据
      this.getQuestion()
    },
    handleSizeChange(pageSize) {
      this.tablePage.pageSize = pageSize
      // 在此刷新数据
      this.getQuestion()
    },

    //获取问题表
    getQuestion() {
      // console.log(this.tablePage.pageNum, this.tablePage.pageSize, this.value);
      getQuestionAPI(this.tablePage.pageNum, this.tablePage.pageSize, this.value).then((res) => {
        this.tableData = res.data.records  //分页结果列表
        this.tablePage.total = res.data.total //总页数
      })
    },
    // 表内选择按钮
    selectHandle(selobject, selectedId, row) {
      if (selobject === '题目') {
        this.submittedAssignments.questionId = selectedId
        this.$message.info('选择了' + selobject + ':' + selectedId)
      } else if (selobject === '作业') {
        // 确保endTime不为空
        if (row.endTime && row.startTime) {
          // 将endTime字符串转换为日期对象
          const startTimeDate = new Date(row.startTime);
          const endTimeDate = new Date(row.endTime);
          // 获取当前时间
          const now = new Date();

          // 比较当前时间是否小于endTime
          if (now > startTimeDate && now < endTimeDate) {
            // 当前时间小于endTime，可以进行删除操作或其他逻辑
            // console.log('当前时间小于endTime，可以执行删除操作。');
            this.submittedAssignments.assignmentId = selectedId
            this.$message.info('选择了' + selobject + ':' + selectedId)
          } else {
            // 当前时间不小于endTime，不能执行删除操作
            // console.log('当前时间不小于endTime，不能执行删除操作。');
            this.$message.error('不在提交作业时间范围内')
          }
        } else {
          // endTime为空，不能进行时间比较
          console.log('endTime为空，无法进行比较。');
        }
      }
    },
    // 答题按钮
    addHandle() {
      this.dialogVisible = true
    },
    //确认上传文件
    submitUpload() {
      this.$refs.upload02.submit();
    },
    // 文件上传处理
    handleSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.$message.success('上传题目内容文件成功');
        // 假设 response.data 是上传成功后的文件链接
        this.submittedAssignments.submissioUrl = response.data;
        console.log('题目内容文件上传成功，文件链接：', response.data);
      } else {
        this.$message.error(`文件上传失败，${response.message}`);
      }
    },
    handleError(err, file, fileList) {
      this.$message.error(`文件上传失败，${err}`);
    },
    // 提交作业
    confirm() {
      // 检查必须的参数是否已提供
      if (!this.submittedAssignments.assignmentId) {
        this.$message.error('未选择作业')
        return false
      }
      if (!this.submittedAssignments.questionId) {
        this.$message.error('未选择题目')
        return false
      }
      if (!this.submittedAssignments.submissioUrl) {
        this.$message.error('未选上传文件')
        return false
      }
      console.log(this.submittedAssignments);
      addSubmittedAssignmentsAPI(this.submittedAssignments).then((res) => {
        if (res.code === 200) {
          if (res.data === 30010) {
            this.$message.error('提交失败，学生已提交该作业')
            return false
          } else if (res.data === 30012) {
            this.$message.error('作业已经过了截止时间，不允提交')
            return false
          }
          this.reset()
          this.$message.success(res.message)
          this.dialogVisible = false
        } else {
          this.$message.error('提交失败')
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    // 重置提交作业
    reset() {
      this.submittedAssignments.assignmentId = '',
      this.submittedAssignments.questionId = '',
      this.submittedAssignments.submissioUrl = '',
      this.fileList = []
    },
    // 返回上一页
    exitAssignment() {
      this.$router.push({
        path: '/student/lesson/manage',
      });
    }
  }
}
</script>

<style scoped>
.wts-container {
  width: 100vw;
  /* 视口宽度 */
  height: 100vh;

  /* 视口高度 */
  .modify-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }
}



/* /deep/  */
.el-radio-button__inner {
  width: 80px;
  /* 深度选择器 定义题目按钮的宽度 */
  height: 40px;
  /* 根据需要调整高度 */
}

.do-assignment {
  display: flex;
  width: 100%;
  /* 使其宽度占满整个.wts-container */
  height: 100%;
  /* 使其高度占满整个.wts-container */
  background: #F2F3F5;

  .assignment-select {
    display: inline-block;
    width: 430px;
  }

  .radio-group {
    display: flex;
    flex-wrap: wrap;
    /* 允许换行 */
    width: 100%;
    justify-content: flex-start;
    /* 从起始位置开始排列子项 */
  }

  /*返回上一级*/

  .assignment-up-page {
    margin: 16px;
    font-size: 14px;
    font-weight: 700;
    color: #999999;
    line-height: 18px;
    cursor: pointer
  }

  .assignment-center {
    /* //display: flex; */
    background-color: #FFFFFF;
    /* //height: 780px; */
    height: 100%;
    margin-left: 36px;
    margin-right: 32px;
    padding-top: 22px;
    overflow: hidden;
    /* 隐藏超出容器的内容 */
    /* 题目信息 */

    .topic-style {
      font-size: 16px;
      font-weight: 600;
      color: #333333;
      line-height: 22px;
    }

    .topic-information {
      font-size: 14px;
      font-weight: 400;
      color: #999999;
      line-height: 20px;
      padding-top: 8px;
    }

    /* 题目内容 */

    .radio-type {
      height: 184px;
      border-top: solid 1px #e6e6e6;
      padding: 15px 40px;
      min-width: 100%;
      /* 确保宽度至少与父元素相同 */
      min-height: 184px;
      /* 确保最小高度 */
      max-height: 184px;
      /* 确保最大高度 */

      .el-radio-group {
        display: block;
        padding: 5px 15px;
      }
    }

    .checkbox-type {
      height: 184px;
      border-top: solid 1px #e6e6e6;
      padding: 15px 40px;
      min-width: 100%;
      /* 确保宽度至少与父元素相同 */
      min-height: 184px;
      /* 确保最小高度 */
      max-height: 184px;
      /* 确保最大高度 */

      .el-checkbox {
        width: 100%;
        padding: 5px 15px;
      }
    }

    .blank-type {
      height: 184px;
      border-top: solid 1px #e6e6e6;
      padding: 15px 40px;
      min-width: 100%;
      /* 确保宽度至少与父元素相同 */
      min-height: 184px;
      /* 确保最小高度 */
      max-height: 184px;
      /* 确保最大高度 */
    }

    .answer-type {
      height: 184px;
      border-top: solid 1px #e6e6e6;
      padding: 15px 40px;
      min-width: 100%;
      /* 确保宽度至少与父元素相同 */
      min-height: 184px;
      /* 确保最小高度 */
      max-height: 184px;
      /* 确保最大高度 */
    }

    .right {
      display: flex;
      justify-content: flex-end;
      /* 使用 flex-end 而不是 right */
      margin-right: 2%;
    }

  }

  /*按钮样式*/

  .button-style {
    display: flex;
    /* Flex 容器，用于内部对齐按钮 */
    justify-content: center;
    /* 水平居中按钮 */
    padding-top: 20px;
    /* 与上面的内容分隔 */
    border-top: dotted 1px #e6e6e6;
    /* 顶部边框 */
    margin-top: auto;
    /* 自动外边距，将按钮推到容器底部 */
  }
}
</style>
